<script setup lang="ts">
import { XYCoord, useDragLayer } from "vue3-dnd";
import { ItemTypes } from "./ItemTypes";
import BoxDragPreview from "./BoxDragPreview.vue";
import { snapToGrid } from "./snapToGrid";
import { toRefs } from "@vueuse/core";
import Box from "./Box.vue";

function getItemStyles(initialOffset: XYCoord | null, currentOffset: XYCoord | null, isSnapToGrid: boolean) {
  if (!initialOffset || !currentOffset) {
    return {
      display: "none",
    };
  }

  let { x, y } = currentOffset;

  if (isSnapToGrid) {
    x -= initialOffset.x;
    y -= initialOffset.y;
    [x, y] = snapToGrid(x, y);
    x += initialOffset.x;
    y += initialOffset.y;
  }

  const transform = `translate(${x}px, ${y}px)`;
  return {
    transform,
  };
}

const props = defineProps<{
  snapToGrid: boolean;
}>();

const collect = useDragLayer((monitor) => ({
  item: monitor.getItem(),
  itemType: monitor.getItemType(),
  initialOffset: monitor.getInitialSourceClientOffset(),
  currentOffset: monitor.getSourceClientOffset(),
  isDragging: monitor.isDragging(),
}));
const { itemType, isDragging, item, initialOffset, currentOffset } = toRefs(collect);

setInterval(() => {
  console.log("itemType", itemType.value, item.value, initialOffset.value, currentOffset.value);
}, 500);
</script>

<template>
  <div class="layer">
    <div :style="getItemStyles(initialOffset, currentOffset, props.snapToGrid)">
      <div class="box-drag-preview" v-if="itemType === ItemTypes.BOX">
        <Box :title="item.title" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.layer {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.box-drag-preview {
  display: inline-block;
}
</style>
